﻿using SuperSocket.ProtoBase;
using System.Buffers;
using System.Text;

namespace SuperSocket.Client.HttpCode;

internal sealed class HttpPackageEncoder : IPackageEncoder<HttpRequestItem>
{
    private const string _get = "GET ";
    private const string _post = "POST ";
    private const string _and = ": ";
    private const string _http1_1 = " HTTP/1.1";
    private static readonly Encoding Utf8Encoding = Encoding.UTF8;

    public int Encode(IBufferWriter<byte> writer, HttpRequestItem request)
    {
        var totalBytes = 0;

        #region url链接

        if (request.Method == HttpCode.HttpMethod.Get)
            totalBytes += writer.Write(_get, Utf8Encoding);
        else
            totalBytes += writer.Write(_post, Utf8Encoding);

        totalBytes += writer.Write(request.Uri.PathAndQuery, request.Encoding);
        totalBytes += writer.Write(_http1_1, Utf8Encoding);
        totalBytes += writer.WriterLine();

        #endregion

        #region 协议头

        var headerCollection = request.GetWebHeader();

        foreach (var key in headerCollection.AllKeys)
        {
            totalBytes += writer.Write(key, request.Encoding);
            totalBytes += writer.Write(_and, Utf8Encoding);
            totalBytes += writer.Write(headerCollection[key], request.Encoding);
            totalBytes += writer.WriterLine();
        }

        totalBytes += writer.WriterLine();

        #endregion

        if (request.Method == HttpCode.HttpMethod.Get)
            return totalBytes;

        if (string.IsNullOrEmpty(request.Content))
        {
            writer.Write(request.Raw);
            totalBytes += request.Raw.Length;
        }
        else
        {
            totalBytes += writer.Write(request.Content, request.Encoding);
        }

        return totalBytes;
    }
}